package com.shimao.celnet.payment.service.impl;

import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.form.SelectTree;
import com.shimao.celnet.payment.mapper.IAppInterfaceAsynMapper;
import com.shimao.celnet.payment.mapper.IAppInterfaceMapper;
import com.shimao.celnet.payment.mapper.IAppMapper;
import com.shimao.celnet.payment.mapper.IInterfaceMapper;
import com.shimao.celnet.payment.model.IApp;
import com.shimao.celnet.payment.model.IAppInterface;
import com.shimao.celnet.payment.model.IAppInterfaceAsyn;
import com.shimao.celnet.payment.model.IInterface;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;


/**
 * 接口注册 管理
 * Created by ensure on 2017/12/3.
 */
@Service
public class IAppInterfaceServiceImpl extends BaseServiceImpl<IAppInterface> implements IAppInterfaceService {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired(required = false)//应用系统接口
    private IAppInterfaceMapper localMapper;

    @Autowired(required = false)//异步返回接口
    private IAppInterfaceAsynMapper iAppInterfaceAsynMapper;

    @Autowired(required = false)//应用系统
    private IAppMapper iAppMapper;

    @Autowired(required = false)//接口
    private IInterfaceMapper iInterfaceMapper;

    /**
     * 分页查询
     * @param formBean
     * @param pageNum
     * @param length
     * @return
     */
    @Override
    public IAppInterfaceForm getByPage(IAppInterfaceForm formBean, int pageNum, int length) {
        logger.info("分页查询--开始");

        //分页查询
        Map<String,String> pMap = new HashMap<String,String>();
        pMap.put("appGuid",formBean.getAppGuid());//应用系统
        pMap.put("interfaceGuid",formBean.getInterfaceId());//接口
        pMap.put("enableFlg","0");//也查询没有启用的接口，应用

        //分页查询
        PageHelper.startPage(pageNum, length);

        List<IAppInterfaceForm> tableList = localMapper.selectByMap(pMap);

        formBean.setPageInfo(tableList);

        //应用系统：列表取得
        formBean.setAppList(iAppMapper.selectAll());
        //接口：列表取得
        formBean.setInterfaceList(iInterfaceMapper.selectAll());

        return  formBean;
    }

    /**
     *新增保存
     * @return
     */
    @Override
    public int save(IAppInterface sBean){
        int retCnt=0;
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        sBean.setUpdateUserGuid(loginUserGuid);
        sBean.setCreatedUserGuid(loginUserGuid);
        sBean.setGuid(getGuid());//guid

        //应用系统<i_app>.访问系统根url
        IApp iApp = new IApp();
        iApp.setGuid(sBean.getAppGuid());
        String appUrl = iAppMapper.selectByPrimaryKey(iApp).getAppUrl();

        //接口信息<i_interface>.访问接口url
        IInterface iInterface = new IInterface();
        iInterface.setGuid(sBean.getInterfaceGuid());
        String iInterfaceUrl =iInterfaceMapper.selectByPrimaryKey(iInterface).getInterfaceUrl();

        //访问url = 应用系统<i_app>.访问系统根url + 接口信息<i_interface>.访问接口url
        sBean.setRequestUrl(appUrl+iInterfaceUrl);
        //系统接口url更新:默认为空，需要修改时如果有数据，访问url=应用系统<i_app>.访问系统根url + 系统接口url
        if(StringUtils.isNotEmpty(sBean.getInterfaceReplaceUrl())){
            sBean.setRequestUrl(appUrl+sBean.getInterfaceReplaceUrl());
        }
        retCnt = super.save(sBean);

        return retCnt;
    }

    /**
     *修改保存
     * @return
     */
    @Override
    public int update(IAppInterface sBean){
        int retCnt=0;
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        sBean.setUpdateUserGuid(loginUserGuid);

        //应用系统<i_app>.访问系统根ur
        IApp iApp = new IApp();
        iApp.setGuid(sBean.getAppGuid());
        String appUrl = iAppMapper.selectByPrimaryKey(iApp).getAppUrl();

        //接口信息<i_interface>.访问接口url
        IInterface iInterface = new IInterface();
        iInterface.setGuid(sBean.getInterfaceGuid());
        String iInterfaceUrl =iInterfaceMapper.selectByPrimaryKey(iInterface).getInterfaceUrl();

        //访问url = 应用系统<i_app>.访问系统根url + 接口信息<i_interface>.访问接口url
        sBean.setRequestUrl(appUrl+iInterfaceUrl);
        //系统接口url更新:默认为空，需要修改时如果有数据，访问url=应用系统<i_app>.访问系统根url + 系统接口url
        if(StringUtils.isNotEmpty(sBean.getInterfaceReplaceUrl())){
            sBean.setRequestUrl(appUrl+sBean.getInterfaceReplaceUrl());
        }
        retCnt = super.update(sBean);

        return retCnt;
    }

    /**
     *修改接口对应异步返回应用接口保存
     * @return
     * @param mainGuid
     * @param retGuidMap
     */
    @Override
    public int updateRet(String mainGuid,Map<String, String> retGuidMap){
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        int retCnt =0;
        //接口对应异步返回接口取得
        Example delExample = new Example(IAppInterfaceAsyn.class);
        Example.Criteria criteria = delExample.createCriteria();
        //主应用接口guid
        criteria.andEqualTo("appInterfaceGuid",mainGuid);
        iAppInterfaceAsynMapper.deleteByExample(delExample);
        //接口对应异步返回接口插入
        for (String appInterfaceGuid : retGuidMap.keySet()) {
            IAppInterfaceAsyn inBean = new IAppInterfaceAsyn();
            inBean.setGuid(iAppInterfaceAsynMapper.selectGuid());
            inBean.setAppInterfaceGuid(mainGuid);
            inBean.setReturnAppInterfaceGuid(appInterfaceGuid);
            inBean.setUpdateUserGuid(loginUserGuid);
            inBean.setCreatedUserGuid(loginUserGuid);
            retCnt+= iAppInterfaceAsynMapper.insert(inBean);
        }
        return retCnt;
    }

    /**
     * 取得详情
     * @param pMap
     * @return
     */
    @Override
    public IAppInterfaceForm getInfoByMap(Map<String,String> pMap){

        IAppInterfaceForm retBean = localMapper.selectByMap(pMap).get(0);
        retBean.setTreeList(this.creatAppInterfaceTree(retBean.getGuid()));
        return retBean;
    }

    /**
     * 根据应用系统编号，接口编号，取得应用系统，接口注册信息
     * @param appKey
     * @param interfaceKey
     * @return
     */
    @Override
    public IAppInterfaceForm getInfoByAppIfKey(String appKey,String interfaceKey){
        Map<String,String> pMap = new HashMap<String,String>();
        pMap.put("appKey",appKey);//应用系统appKey
        pMap.put("interfaceId",interfaceKey);//接口编号
        pMap.put("enableFlg","1");//查询启用的接口，应用

        IAppInterfaceForm retBean = localMapper.selectByMap(pMap).get(0);

        return retBean;
    }

    /**
     * 检查接口请求是否有权限，
     * @param pMap:条件：接口api，接口编号，应用编号
     * @return AppToken
     */
    @Override
    public String getAppToken(Map<String,String> pMap){
        pMap.put("enableFlg","1");//只查询启用的接口，应用
        List<IAppInterfaceForm> ifList= localMapper.selectByMap(pMap);
        System.out.println(ifList);
        if(ifList.size()>0){
            return ifList.get(0).getAppToken();
        }else{
            return "";
        }
    }

    /**
     * 异步返回接口树生成
     * @param mainGuid 主接口guid
     * @return
     */
    @Override
    public  List<SelectTree>  creatAppInterfaceTree(String mainGuid) {

        //异步返回接口列表获取
        Map<String, String> retGuidMap = new HashMap<String, String>();
        List<IAppInterfaceForm> retList =getRetAppInterface(mainGuid);
        if(retList.size() > 0) {
            for (IAppInterfaceForm retBean : retList) {
                retGuidMap.put(retBean.getGuid(), retBean.getGuid());
            }
        }

        //全部应用接口取得
        Map<String,String> pMap = new HashMap<String,String>();
        List<IAppInterfaceForm> localBeanAll = localMapper.selectByMap(pMap);
        Collections.sort(localBeanAll, new SortByAppKey());
        List<SelectTree> retTreeList = new ArrayList<SelectTree>();
        for(IAppInterfaceForm retBean:localBeanAll){
            SelectTree selectTree = new SelectTree();
            //异步返回接口选择
            selectTree.setDataSection(FinalUtil.RETURN_APP_INTERFACE_ROOT);//父级名称
            //应用系统名称(应用系统编号)-接口名称(接口编号-接口api)
            selectTree.setGuid(retBean.getGuid());//节点value
            StringBuffer treeName = new StringBuffer(retBean.getAppName());
            treeName.append("(");
            treeName.append(retBean.getAppKey());
            treeName.append(")-");
            treeName.append(retBean.getInterfaceName());
            treeName.append("(");
            treeName.append(retBean.getInterfaceId());
            treeName.append("-");
            treeName.append(retBean.getInterfaceApi());
            treeName.append(")");
            selectTree.setOptionText(treeName.toString());//树节点名称
            selectTree.setStrSelected(FinalUtil.DISABLE);//无权限
            if(StringUtils.isNotEmpty(retGuidMap.get(retBean.getGuid()))) {
                selectTree.setStrSelected(FinalUtil.ENABLE);//有权限
            }
            retTreeList.add(selectTree);

        }

        return retTreeList;
    }

    class SortByAppKey implements Comparator {
        public int compare(Object o1, Object o2) {
            IAppInterfaceForm s1 = (IAppInterfaceForm) o1;
            IAppInterfaceForm s2 = (IAppInterfaceForm) o2;
            return s1.getAppKey().compareTo(s2.getAppKey());
        }
    }

    /**
     * 异步返回接口列表获取
     * @param mainGuid 主接口guid
     * @return
     */
    @Override
    public  List<IAppInterfaceForm> getRetAppInterface(String mainGuid) {
        //接口对应异步返回接口取得
        Map<String,String> pMap = new HashMap<String,String>();
        pMap.put("appInterfaceGuid", mainGuid);
        return ListUtils.defaultIfNull( localMapper.selectByMap(pMap), new ArrayList<IAppInterfaceForm>());
    }
}
